﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.ComponentModel;
using System.Reflection;

namespace Lib
{
    public static class Collections
    {
        public static DataTable ConvertToDataTable<T>(IList<T> data)
        {
            PropertyDescriptorCollection properties =
               TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;

        }
        public static void ConvertDataRowtoObject(DataRow dataRow, Object objectType)
        {
            //--- o type é necessário para obter as propriedades do objecto
            Type t = objectType.GetType();

            //--- obtem as propriedades o objecto
            PropertyInfo[] propertiesList = t.GetProperties();

            foreach (PropertyInfo properties in propertiesList)
            {
                try
                {
                    //--- coloca o valor da datarow na propriedade correcta do objecto
                    t.InvokeMember(properties.Name, BindingFlags.SetProperty, null,
                                    objectType,
                                    new object[] { dataRow[properties.Name] });
                }
                catch (Exception ex)
                {
                    //--- Se deu erro é porque a propriedade não existe na datarow ou porque o valor é nulo
                    if (ex.ToString() != null) { }
                }
            }
        }
        public static DataRow ConvertObjectToDataRow(DataTable dt,Object obj)
        {
            Type t = obj.GetType();
            PropertyInfo[] propertiesList = t.GetProperties();
            DataRow r = dt.NewRow();
            try
            {
                foreach (PropertyInfo properties in propertiesList)
                {
                    r[properties.Name] = properties.GetValue(obj, null);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return r;
        }
    }
}
